from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from utils.scheduled_tasks import cleanup_expired_articles

# 全局调度器实例
scheduler = None


def start_scheduler():
    """启动定时任务调度器"""
    global scheduler

    if scheduler is not None:
        print("The scheduler is already running")
        return

    try:
        # 创建后台调度器
        scheduler = BackgroundScheduler()

        # 添加文章置顶过期检查任务 - 每1分钟执行一次
        scheduler.add_job(
            func=cleanup_expired_articles,
            trigger=IntervalTrigger(minutes=1),
            id='expire_articles_job',
            name='Check if the top of the article has expired',
            replace_existing=True,
            max_instances=1
        )

        # 启动调度器
        scheduler.start()
        print("The scheduled task scheduler has been started")

    except Exception as e:
        print(f"An error occurred while starting the scheduler: {e}")
        raise e


def stop_scheduler():
    """停止定时任务调度器"""
    global scheduler

    if scheduler is not None:
        try:
            scheduler.shutdown()
            scheduler = None
            print("The scheduled task scheduler has stopped")
        except Exception as e:
            print(f"An error occurred while stopping the scheduler: {e}")


def get_scheduler_status():
    """获取调度器状态"""
    global scheduler

    if scheduler is None:
        return {"status": "stopped", "jobs": []}

    jobs = []
    for job in scheduler.get_jobs():
        jobs.append({
            "id": job.id,
            "name": job.name,
            "next_run_time": str(job.next_run_time) if job.next_run_time else None,
            "trigger": str(job.trigger)
        })

    return {
        "status": "running" if scheduler.running else "stopped",
        "jobs": jobs
    }


def restart_scheduler():
    """重启调度器"""
    stop_scheduler()
    start_scheduler()